<template>
<div class="tree">
    <a-tree
    v-model="checkedKeys"
    checkable
    :expanded-keys="expandedKeys"
    :auto-expand-parent="autoExpandParent"
    :selected-keys="selectedKeys"
    :tree-data="noLeafData"
    @expand="onExpand"
    @select="onSelect"
    @check="onCheck"
    :replaceFields="{
      key:'code'
    }"
  />
  </div>
</template>
<script>
export default {
  name:'treeMenu',
  props:{
    treeData:{
      type:Array,
      default:null
    },
    currentChecked:{
      type:Array,
      default:null
    }
  },
  data() {
    return {
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      noLeafData:[]
    }
  },
  watch:{
    treeData:{
      handler(newValue, oldValue) {
        const data = JSON.parse(JSON.stringify(newValue))
        this.noLeafData=this.del(data)
      },
      deep:true
    },
    currentChecked(newValue, oldValue){
      console.log(newValue, oldValue)
      this.checkedKeys = newValue
    }
  },
  mounted() {
    const data = JSON.parse(JSON.stringify(this.treeData))
    this.noLeafData=this.del(data)
    this.checkedKeys = this.currentChecked
  },
  methods: {
    del(arr){
      for (let item of arr) {
        if(!item.leaf){
          let result = item.children.filter(value => value.leaf)
          if(result.length==item.children.length){
            delete item.children
          }else {
            this.del(item.children)
          }
        }
      }
      return arr
    },
    onExpand(expandedKeys) {
      // console.log('onExpand', expandedKeys);
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      console.log('onCheck', checkedKeys);
      this.checkedKeys = checkedKeys;
      // console.log(this.checkedKeys)
      this.$emit('updateTags',checkedKeys)
    },
    onSelect(selectedKeys, info) {
      // console.log('onSelect', info);
      this.selectedKeys = selectedKeys;
    },
  },
}
</script>
<style lang="less" scoped>
  .tree{
    span{
      margin-right: 12px;
      margin-left: 0px;
    }
  }
</style>